package com.xiangxiao.rpan.storage.helper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiangxiao.rpan.storage.cache.redis.RedisCache;
import com.xiangxiao.rpan.storage.constant.ResponseCode;
import com.xiangxiao.rpan.storage.constant.ResponseMessage;
import com.xiangxiao.rpan.storage.entity.UserInfo;
import com.xiangxiao.rpan.storage.exception.StorageExcetion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @ClassName UserInfoHelper
 * @Auther admin
 * @Email 573768011@qq.com
 * @Date 2024/1/16 17:35
 */
@Component
public class UserInfoHelper {
  private static final Logger log = LoggerFactory.getLogger(UserInfoHelper.class);
  @Autowired
  private StringRedisTemplate redisTemplate;


  public UserInfoHelper() {
  }

  public UserInfo getUserInfo(String token) throws StorageExcetion {
    try {
      String str = token.replace(String.valueOf("Bearer "), "");
      UserInfo userInfo = JSONObject.parseObject(redisTemplate.opsForValue().get(str), UserInfo.class);
      if (userInfo == null) {
        throw new StorageExcetion(ResponseMessage.NOT_FIND_LOGGED_USERINO, ResponseCode.NOT_FIND_LOGGED_USERINO);
      };
      return userInfo;
    } catch (Exception e) {
      e.printStackTrace();
      throw new StorageExcetion(e.getMessage(), ResponseCode.NOT_FIND_LOGGED_USERINO);
    }
  }

  public Long getUserIdByToken(String token) throws StorageExcetion {
    UserInfo userInfo = this.getUserInfo(token);
    return userInfo.getUserVo().getId();
  }
}
